package com.gin.no_gay_alliance.fragment.user;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.adapter.FragmentStateAdapter;

import com.gin.common.utils.StrUtils;
import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.exception.NgaClientException;
import com.gin.nga.exception.NgaException;
import com.gin.nga.response.field.user.UserInfoNuke;
import com.gin.no_gay_alliance.R;
import com.gin.no_gay_alliance.activity.UserCenterActivity;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.databinding.FragmentUserCenterBinding;
import com.gin.no_gay_alliance.enums.MessageWhat;
import com.gin.no_gay_alliance.exception.RequireParamException;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.fragment.user.tab.ConfigBlockDataFragment;
import com.gin.no_gay_alliance.fragment.user.tab.UserInfoExtraTabFragment;
import com.gin.no_gay_alliance.fragment.user.tab.UserInfoTabFragment;
import com.gin.no_gay_alliance.fragment.user.tab.UserIpLocationFragment;
import com.gin.no_gay_alliance.fragment.user.tab.UserItemTabFragment;
import com.gin.no_gay_alliance.fragment.user.tab.UserRecentTopicTabFragment;
import com.gin.no_gay_alliance.fragment.user.tab.UserSignatureTabFragment;
import com.gin.no_gay_alliance.manager.UserInfoManager;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.InputMethodManagerUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;
import com.gin.no_gay_alliance.viewmodel.UserInfoModel;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.io.IOException;
import java.io.Serializable;

import okhttp3.Call;

/**
 * 用户中心
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/8/10 11:14
 **/
public class UserCenterFragment extends BaseBindingFragment<FragmentUserCenterBinding> implements Callback<UserInfoNuke> {
    public static final String ARG_USER_ID = "uid";
    public static final String ARG_USERNAME = "username";
    private Long userId;
    private String username;
    private UserInfoModel userInfoModel;
    private TabLayoutMediator tabLayoutMediator;

    @Override
    public void onResume() {
        super.onResume();

        // 从参数中获取用户id或用户名
        Bundle arguments = getArguments();
        if (arguments != null) {
            if (this.userId != null && this.userId == arguments.getLong(ARG_USER_ID)) {
                // 如果之前已经请求过数据，且用户id未变化，不执行请求
                return;
            }
            this.userId = arguments.getLong(ARG_USER_ID, -1L);
            this.username = arguments.getString(ARG_USERNAME, "");
            sendRequest(false);
        } else {
            throw new RequireParamException();
        }
    }

    /**
     * onCreateView 的后续操作
     */
    @Override
    protected void onCreateView() {

    }

    /**
     * 配置 TabLayout
     *
     * @param tab      标签
     * @param position 位置
     */
    @Override
    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
        switch (position) {
            case 0:
                tab.setText("基础");
                break;
            case 1:
                tab.setText("额外");
                break;
            case 2:
                tab.setText("主题");
                break;
            case 3:
                tab.setText("签名");
                break;
            case 4:
                tab.setText("IP属地");
                break;
            case 5:
                tab.setText("屏蔽");
                break;
            case 6:
                tab.setText("道具");
                break;
            default:
                throw new RuntimeException("没有那个功能:" + position);
        }
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.refresh_menu, menu);
        inflater.inflate(R.menu.search_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == R.id.menu_item_refresh) {
            sendRequest(true);
        }
        if (item.getItemId() == R.id.menu_item_search) {
            // TODO: 2023/9/23 以用户ID或用户名打开其他用户中心

            EditText et = new EditText(requireContext());
            et.setHint(R.string.message_search_user);

            AlertDialog dialog = AlertDialogUtils.showConfirm(requireContext(), "搜索用户", getString(R.string.message_search_user), et, (d, which) -> {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    String text = String.valueOf(et.getText());
                    if (StrUtils.isNumber(text)) {
                        UserCenterActivity.startActivity(requireContext(), Long.parseLong(text));
                    } else {
                        UserCenterActivity.startActivity(requireContext(), text);
                    }
                }
            });
            // 自动获取焦点
            et.requestFocus();
            InputMethodManagerUtils.show(handler, et);

            //输入校验
            Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
            et.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    button.setEnabled(!ObjectUtils.isEmpty(s));
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 请求成功回调
     *
     * @param data 数据
     */
    @Override
    public void onSuccess(UserInfoNuke data) {
        long currentUserId = MyApplication.getClient().getUserId();
        this.userId = data.getUserId();
        userInfoModel = new UserInfoModel(data);

        // 更新标题
        getParentHandler().sendMessage(MessageWhat.UPDATE_TOOLBAR_TITLE, data.getUsername());

        ui(() -> {
            ViewUtils.setGone(false, b.vp2, b.tabLayout);
            ViewUtils.setGone(true, b.tvWarning, b.progressBar);

            // 装载ViewPager2
            b.vp2.setAdapter(new FragmentStateAdapter(this) {
                @NonNull
                @Override
                public Fragment createFragment(int position) {
                    switch (position) {
                        case 0:
                            return UserInfoTabFragment.newInstance(userInfoModel);
                        case 1:
                            return UserInfoExtraTabFragment.newInstance(userInfoModel);
                        case 2:
                            return UserRecentTopicTabFragment.newInstance(userInfoModel);
                        case 3:
                            return UserSignatureTabFragment.newInstance(userInfoModel);
                        case 4:
                            return UserIpLocationFragment.newInstance(userId);
                        case 5:
                            return new ConfigBlockDataFragment();
                        case 6:
                            // 道具标签，仅在自己的用户中心出现
                            return UserItemTabFragment.newInstance();
                        default:
                            throw new RuntimeException("没有那个功能:" + position);
                    }
                }

                @Override
                public int getItemCount() {
                    return 5 + (currentUserId == data.getUserId() ? 2 : 0);
                }
            });

            tabLayoutMediator = attachTabLayout(tabLayoutMediator, b.tabLayout, b.vp2);

            // 临时设置初始位置
//            vp2.setCurrentItem(2, false);
        });
    }

    /**
     * 请求之前执行的操作
     */
    @Override
    public void beforeRequest() {
        Callback.super.beforeRequest();

        // 显示加载动画
        b.progressBar.setVisibility(View.VISIBLE);
        ViewUtils.setGone(true, b.tvWarning, b.vp2, b.tabLayout);
    }

    /**
     * 请求失败回调(一般为网络访问错误)
     *
     * @param call call
     * @param e    错误
     */
    @Override
    public void onFailure(@NonNull Call call, @NonNull IOException e) {
        showWarning(e);
    }

    /**
     * 处理Nga异常
     *
     * @param e 异常
     */
    @Override
    public void handleException(NgaException e) {
        showWarning(e);
    }

    /**
     *
     */
    private void sendRequest(boolean ignoreCache) {
        UserInfoManager userInfoManager = MyApplication.app.managerFactory.getUserInfoManager();
        userInfoManager.request(ignoreCache, this.userId, this.username, this);
    }

    /**
     * 显示报错提示，隐藏主题列表
     *
     * @param e 异常
     */
    private void showWarning(IOException e) {
        String msg = (e instanceof NgaClientException) ? ((NgaClientException) e).getReason().get(0) : e.getMessage();
        ui(() -> {
            ViewUtils.setGone(true, b.progressBar, b.vp2, b.tabLayout);
            b.tvWarning.setVisibility(View.VISIBLE);
            b.tvWarning.setText(msg);
        });
    }

    /**
     * 初始化
     *
     * @param identifier userid 或 username
     * @return
     */
    public static UserCenterFragment getInstance(Serializable... identifier) {
        UserCenterFragment fragment = new UserCenterFragment();
        Bundle args = new Bundle();
        for (Serializable s : identifier) {
            if (s instanceof Long && (Long) s > 0) {
                args.putLong(ARG_USER_ID, (Long) s);
            }
            if (s instanceof String) {
                args.putString(ARG_USERNAME, String.valueOf(s));
            }
        }
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * 设置用户id参数
     *
     * @param userId 用户id
     */
    public void setUserId(long userId) {
        Bundle arguments = getArguments();
        arguments = arguments != null ? arguments : new Bundle();
        arguments.putLong(ARG_USER_ID, userId);
        this.userId = userId;
    }
}
